package com.itcast.googleplay.fragment;

import java.util.List;
import android.view.View;
import android.widget.ListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.itcast.googleplay.R;
import com.itcast.googleplay.adapter.MyBaseAdapter;
import com.itcast.googleplay.bean.AppInfo;
import com.itcast.googleplay.holder.AppHolder;
import com.itcast.googleplay.holder.BaseHolder;
import com.itcast.googleplay.protocol.AppProtocal;
import com.itcast.googleplay.ui.LoadingPage.ResultState;
import com.itcast.googleplay.utils.UIUtils;

public class AppFragment extends BaseFragment {
	private PullToRefreshListView pullToRefreshListView;
	private ListView listView;
	private MyAdapter myAdapter;
	private List<AppInfo> appInfoList;
	
	@Override
	public ResultState onSubLoad() {
		AppProtocal appProtocol = new AppProtocal();
		appInfoList = appProtocol.getData("app", 0, "");
		if(appInfoList!=null){
			return ResultState.STATE_SUCCESSED;
		}
		return ResultState.STATE_ERROR;
	}

	@Override
	public View onCreateSuccessedSubView() {
		pullToRefreshListView = (PullToRefreshListView) UIUtils.inflate(R.layout.layout_refresh_list);
		listView = pullToRefreshListView.getRefreshableView();
		listView.setDivider(null);
		
		initData();
		
		pullToRefreshListView.setMode(Mode.BOTH);
		pullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				refreshOrLoadMore();
			}
		});
		return pullToRefreshListView;
	}


	private void initData() {
		myAdapter = new MyAdapter(appInfoList);
		listView.setAdapter(myAdapter);
	}

	protected void refreshOrLoadMore() {
		if(pullToRefreshListView.getCurrentMode() == Mode.PULL_FROM_START){
			appInfoList.clear();
			showData();
			pullToRefreshListView.onRefreshComplete();
		}else{
			new Thread(){
				public void run() {
					AppProtocal appProtocol = new AppProtocal();
					final List<AppInfo> moreData = appProtocol.getData("app",appInfoList.size(), "");
					UIUtils.runInMainThread(new Runnable() {
						@Override
						public void run() {
							if(moreData.size()>0){
								appInfoList.addAll(moreData);
								myAdapter.notifyDataSetChanged();
								pullToRefreshListView.onRefreshComplete();
							}
						}
					});
				};
			}.start();
		}
	}
	
	class MyAdapter extends MyBaseAdapter<AppInfo>{

		public MyAdapter(List<AppInfo> list) {
			super(list);
		}

		@Override
		public BaseHolder<AppInfo> getHolder() {
			return new AppHolder();
		}
	}

}
